﻿-- Author      : Thorwald Odin
-- Create Date : 12/7/2013 1:59:20 PM
local _, addon = ...;

addon.Item = {};

local Item = addon.Item;

local Item_MetaTable = {
	__index = Item,
};

function Item:Release()
	setmetatable(self, nil);
	addon.tableRecycler:Release(self);
end

Item.New = function(_link, _bag, _slot)
	local item = addon.tableRecycler:Acquire();
	setmetatable(item, Item_MetaTable);
	
	local id = Item.GetID(_link);
	
	local name, link, quality, iLvl, _, type, subType, stackSize, _, _, value = GetItemInfo(id);
	if not name then
		addon:Debug('error', 'Unknown item from link: {1}, {2}, {3}', _link, id, name);
		item:Release();
		return nil;
	end
	item.ID = id;
	item.Name = name;
	item.Link = link;
	item.Quality = quality;
	item.iLevel = iLvl;
	item.Type, item.SubType = 1, 1;
	for i, v in ipairs(addon.ItemTypes) do
		if type == v then
			item.Type = i;
			break;
		end
	end
	for i, v in ipairs(addon.ItemSubTypes[item.Type]) do
		if subType == v then
			item.SubType = i;
			break;
		end
	end
	item.MaxStackSize = stackSize;
	item.Value = value;
		
	local desc = '';
	LootFilterScanningTooltip:SetHyperlink(link);
	
	for i = 1, LootFilterScanningTooltip:NumLines() do
		local left, right = getglobal('LootFilterScanningTooltipTextLeft' .. i), getglobal('LootFilterScanningTooltipTextRight' .. i);
		desc = desc .. ' ' .. left:GetText() .. ' ' .. right:GetText();
	end
	
	item.Desc = desc;
	
	item:FindInfo(_bag, _slot);
	
	return item;
end

Item.GetID = function(link)
	local id = link:match('item:(%d+):');
	addon:Debug('notice', '{1},{2},{3},{4},{5}', link:match('item:(%d+):'));
	return tonumber(id) or 0;
end

function Item:FindInfo(_bag, _slot)
	addon:IterateBagSpace({
		OnBag = function(bag)
			return addon.db.ParseBag[bag + 1]; -- Should check this bag.
		end,
		OnItem = function(bag, slot, link)
			local id = Item.GetID(link);
			if id == self.ID then
				local _, count = GetContainerItemInfo(bag, slot);
				addon:Debug('notice', 'Found {1}x{4} at position {2},{3}', link, bag, slot, count);
				self.Bag = bag;
				self.Slot = slot;
				self.Count = count;
				return false; -- Found the item. Pop out of bag iteration.
			end
			return true; -- Continue searching
		end,
	});
	if self.Bag == nil or self.Slot == nil then
		addon:Debug('warning', 'Could not find `{1}` in any parsed bag', self.Name);
	end
end


